{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The MIT License (MIT)\n",
    "\n",
    "# Copyright (c) 2020, NVIDIA CORPORATION.\n",
    "\n",
    "# Permission is hereby granted, free of charge, to any person obtaining a copy of\n",
    "# this software and associated documentation files (the \"Software\"), to deal in\n",
    "# the Software without restriction, including without limitation the rights to\n",
    "# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n",
    "# the Software, and to permit persons to whom the Software is furnished to do so,\n",
    "# subject to the following conditions:\n",
    "\n",
    "# The above copyright notice and this permission notice shall be included in all\n",
    "# copies or substantial portions of the Software.\n",
    "\n",
    "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
    "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n",
    "# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n",
    "# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n",
    "# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n",
    "# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tutorial: Feature Engineering for Recommender Systems\n",
    "\n",
    "# 0. Initial Data Loading"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In our tutorial, we use the [eCommerce behavior data from multi category store](https://www.kaggle.com/mkechinov/ecommerce-behavior-data-from-multi-category-store) from [REES46 Marketing Platform](https://rees46.com/) as our dataset. We define our own goal and filter the dataset accordingly. This jupyter notebook provides the code to preprocess the dataset and generate the train, validation and test sets for the remainder of the tutorial.<br><br>\n",
    "\n",
    "\n",
    "For our tutorial, we decided that our goal is to predict if a user purchased an item:\n",
    "\n",
    "<li> Positive: User purchased an item\n",
    "<li> Negative: User added an item to the cart, but did not purchase it (in the same session)    \n",
    "<br><br>    \n",
    "We split the dataset into train, validation and test set by the timestamp:\n",
    "<li> Training: October 2019 - February 2020\n",
    "<li> Validation: March 2020\n",
    "<li> Test: April 2020\n",
    "<br><br>\n",
    "We remove AddToCart Events from a session, if in the same session the same item was purchased."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, download all csv files included in the Google Drive folder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import glob"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "list_files = glob.glob('./data/*.csv')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we process a single .csv file and extract/filter the rows"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_files(file):\n",
    "    df_tmp = pd.read_csv(file)\n",
    "    df_tmp['session_purchase'] =  df_tmp['user_session'] + '_' + df_tmp['product_id'].astype(str)\n",
    "    df_purchase = df_tmp[df_tmp['event_type']=='purchase']\n",
    "    df_cart = df_tmp[df_tmp['event_type']=='cart']\n",
    "    df_purchase = df_purchase[df_purchase['session_purchase'].isin(df_cart['session_purchase'])]\n",
    "    df_cart = df_cart[~(df_cart['session_purchase'].isin(df_purchase['session_purchase']))]\n",
    "    df_cart['target'] = 0\n",
    "    df_purchase['target'] = 1\n",
    "    df = pd.concat([df_cart, df_purchase])\n",
    "    df = df.drop('category_id', axis=1)\n",
    "    df = df.drop('session_purchase', axis=1)\n",
    "    df[['cat_0', 'cat_1', 'cat_2', 'cat_3']] = df['category_code'].str.split(\"\\.\", n = 3, expand = True).fillna('NA')\n",
    "    df['brand'] = df['brand'].fillna('NA')\n",
    "    df = df.drop('category_code', axis=1)\n",
    "    df['timestamp'] = pd.to_datetime(df['event_time'].str.replace(' UTC', ''))\n",
    "    df['ts_hour'] = df['timestamp'].dt.hour\n",
    "    df['ts_minute'] = df['timestamp'].dt.minute\n",
    "    df['ts_weekday'] = df['timestamp'].dt.weekday\n",
    "    df['ts_day'] = df['timestamp'].dt.day\n",
    "    df['ts_month'] = df['timestamp'].dt.month\n",
    "    df['ts_year'] = df['timestamp'].dt.year\n",
    "    df.to_csv('./' + file.replace('../data/', ''), index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['./2019-Dec.csv',\n",
       " './2020-Jan.csv',\n",
       " './2020-Feb.csv',\n",
       " './2019-Oct.csv',\n",
       " './2020-Mar.csv',\n",
       " './2020-Apr.csv',\n",
       " './2019-Nov.csv']"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list_files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "for file in list_files:\n",
    "    print(file)\n",
    "    process_files(file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we load all preprocessed csv files, combine them and create our train, validation and test sets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "lp = []\n",
    "list_files = glob.glob('./*.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/conda/envs/rapids/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3146: DtypeWarning: Columns (11) have mixed types.Specify dtype option on import or set low_memory=False.\n",
      "  interactivity=interactivity, compiler=compiler, result=result)\n"
     ]
    }
   ],
   "source": [
    "for file in list_files:\n",
    "    lp.append(pd.read_csv(file))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.concat(lp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(16695562, 19)"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_test = df[df['ts_month']==4]\n",
    "df_valid = df[df['ts_month']==3]\n",
    "df_train = df[(df['ts_month']!=3)&(df['ts_month']!=4)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((11461357, 19), (2461719, 19), (2772486, 19))"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_train.shape, df_valid.shape, df_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_train.to_parquet('./data/train.parquet', index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_valid.to_parquet('./data/valid.parquet', index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_test.to_parquet('./data/test.parquet', index=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
